<%@ page language="java" import="java.util.*"
	contentType="text/html; charset=utf-8"%>
<%@ page import="java.net.URLEncoder" %>
<!-- 引入实体类Users -->	
<jsp:useBean id="loginUser" class="entity.Users"></jsp:useBean>
<!-- 引入业务逻辑类UsersDAO -->
<jsp:useBean id="userDAO" class="dao.UsersDAO"></jsp:useBean>
<%request.setCharacterEncoding("utf-8"); %>
<!-- 为javaBean loginUser设置属性，使用表单自动设置全部的值 -->
<jsp:setProperty property="*" name="loginUser"/>
<%
		//判断用户是否选择了记住密码
		String[] isUseCookie = request.getParameterValues("isUseCookie");
		if (isUseCookie != null && isUseCookie.length > 0) {
			/*把用户名和密码保存在Cookie对象中*/
			//得到登录表单中的内容并编码
			String username = URLEncoder.encode(loginUser.getUsername(), "utf-8");
			String password = URLEncoder.encode(loginUser.getPassword(), "utf-8");
			//创建2个Cookie对象
			Cookie usernameCookie = new Cookie("username", username);
			Cookie passwordCookie = new Cookie("password", password);
			usernameCookie.setMaxAge(3600 * 24 * 10);//设置cookie生存期10天    		
			passwordCookie.setMaxAge(3600 * 24 * 10);

			//在客户端保存Cookie对象，需要依赖response对象的addCookie方法
			response.addCookie(usernameCookie);
			response.addCookie(passwordCookie);
		} else {
			/*使已经保存的cookie对象失效*/
			Cookie[] cookies = request.getCookies();//得到客户端保存的cookie
			if (cookies != null && cookies.length > 0) {
				//遍历Cookie数组
				for (Cookie c : cookies) {
					if (c.getName().equals("username")
							|| c.getName().equals("password")) {
						c.setMaxAge(0);//设置Cookie的有效期是0,让其马上失效
						response.addCookie(c);//重新向客户端保存Cookie
					}
				}
			}
		}
	%>
<!-- 调用业务逻辑代码 -->
<%
	request.setCharacterEncoding("utf-8");//防止中文乱码
	if(userDAO.isUserLogin(loginUser)){
		//如果用户登录成功则向session中设置用户名和密码
		session.setAttribute("username", loginUser.getUsername());
		session.setAttribute("password", loginUser.getPassword());
		//请求转发
		request.getRequestDispatcher("login_success.jsp").forward(request, response);
	}else{
		//重定向
		response.sendRedirect("login_failure.jsp");
	}
%>